/**
 * @Author: easten
 * @Created: 2024-04-15 23:48:14
 * @Description: 网关管理抽屉
 *
 */
import { ApiGateway } from "_common/api/iot";
import { DrawerProps } from "_common/DataType";
import { IotGateway } from "_common/entity";
import { AxiosInstance } from "axios";
import React, { useEffect, useRef } from "react";
import {
  Button,
  Drawer,
  Form,
  FormInstanceFunctions,
  Input,
  InputNumber,
  Radio,
  Select,
} from "tdesign-react";
type GatewayDrawerProps = DrawerProps & {
  axios: AxiosInstance;
};
const GatewayDrawer: React.FC<GatewayDrawerProps> = (
  props: GatewayDrawerProps
) => {
  const { open, edit, onSuccess, value, axios } = props;
  const formRef = useRef<FormInstanceFunctions>();
  const { FormItem } = Form;
  // 列表状态
  const [form] = Form.useForm();
  const gatewayType = Form.useWatch("gatewayType", form);
  const apiGateway = new ApiGateway(axios);
  useEffect(() => {
    // 默认网关类型为tcp
    return () => {
      formRef.current?.reset();
    };
  }, []);

  useEffect(() => {
    // 清空ip ,port 串口号等数据
    formRef.current?.setFields([
      { name: "ipAddress", value: "" },
      { name: "port", value: "" },
      { name: "serialPort", value: "" },
      { name: "baudRate", value: "" },
      { name: "dataBits", value: "" },
      { name: "stopBits", value: "" },
      { name: "parity", value: "" },
    ]);
    if (gatewayType === "Tcp") {
      getTcpConfig();
    }
    if (gatewayType === "SerialPort") {
      getSerialConfig();
    }
  }, [gatewayType]);

  // 获取tcp配置
  const getTcpConfig = async () => {
    const response = await apiGateway.getTcpConfig(value.id);
    if (response && response.code == 200 && response.data) {
      formRef.current?.setFieldsValue(response.data);
    }
  };

  // 获取串口配置
  const getSerialConfig = async () => {
    const response = await apiGateway.getSerialConfig(value.id);
    if (response && response.code == 200 && response.data) {
      formRef.current?.setFieldsValue(response.data);
    }
  };

  useEffect(() => {
    if (value && edit) {
      formRef.current?.setFieldsValue(value);
      if (value.gatewayType === "Tcp") {
        getTcpConfig();
      }
      if (value.gatewayType === "SerialPort") {
        getSerialConfig();
      }
    }
  }, [edit, value]);

  const handleClose = () => {
    onSuccess?.(false);
    formRef.current?.reset();
    formRef.current?.setFieldsValue({ gatewayType: "Tcp" });
  };

  // 新增网关
  const createGateway = async (data: IotGateway) => {
    const response = await apiGateway.crete(data);
    if (response && response.code == 200 && response.data) {
      handleClose();
    }
  };

  // 更新网关
  const updateGateway = async (data: IotGateway) => {
    const response = await apiGateway.update({
      ...data,
      id: value?.id,
      isEnable: value?.isEnable,
    });
    if (response && response.code == 200 && response.data) {
      handleClose();
    }
  };

  return (
    <Drawer
      header={`${edit ? "编辑" : "添加"}网关`}
      footer={false}
      visible={open}
      sizeDraggable
      size="medium"
      onClose={handleClose}
    >
      <Form
        ref={formRef}
        form={form}
        labelWidth={100}
        onSubmit={async (data) => {
          // 是否校验通过
          if ((await formRef.current?.validateOnly()) == true) {
            let body = {
              ...data.fields,
              serialConfig: {
                dataBits: data.fields.dataBits,
                stopBits: data.fields.stopBits,
                parity: data.fields.parity,
                baudRate: data.fields.baudRate,
                serialPort: data.fields.serialPort,
              },
              tcpConfig: {
                ipAddress: data.fields.ipAddress,
                port: data.fields.port,
              },
            };
            edit
              ? updateGateway(body as IotGateway)
              : createGateway(body as IotGateway);
          }
        }}
      >
        <FormItem
          label="网关名称"
          rules={[{ required: true }]}
          name="gatewayName"
        >
          <Input />
        </FormItem>
        <FormItem
          label="网关编码"
          rules={[{ required: true }]}
          name="gatewayCode"
        >
          <Input />
        </FormItem>
        <FormItem
          label="网关描述"
          rules={[{ required: false }]}
          name="gatewayDesc"
        >
          <Input />
        </FormItem>
        <FormItem
          label="采集频率（秒）"
          rules={[{ required: false }]}
          name="frequency"
        >
          <InputNumber />
        </FormItem>
        <FormItem
          label="网关类型"
          rules={[{ required: false }]}
          name="gatewayType"
        >
          <Radio.Group>
            <Radio.Button value={"Tcp"}>Tcp网关</Radio.Button>
            <Radio.Button value={"SerialPort"}>串口网关</Radio.Button>
          </Radio.Group>
        </FormItem>
        {gatewayType === "SerialPort" ? (
          <>
            <FormItem
              label="串口号"
              rules={[
                { required: true },
                {
                  pattern: /^COM[1-9]\d*$/,
                  message: "请输入正确的串口号",
                },
              ]}
              name="serialPort"
            >
              <Select
                options={Array.from({ length: 20 }, (_v, i) => ({
                  label: `COM${i + 1}`,
                  value: `COM${i + 1}`,
                }))}
              />
            </FormItem>
            <FormItem
              label="波特率"
              rules={[{ required: true }]}
              name="baudRate"
            >
              <Select
                options={[
                  { label: "4800", value: 4800 },
                  { label: "9600", value: 9600 },
                  { label: "14400", value: 14400 },
                  { label: "19200", value: 19200 },
                  { label: "38400", value: 38400 },
                  { label: "57600", value: 57600 },
                  { label: "115200", value: 115200 },
                ]}
              />
            </FormItem>
            <FormItem
              label="数据位"
              rules={[{ required: false }]}
              name="dataBits"
            >
              <Select
                options={[
                  { label: "5", value: 5 },
                  { label: "6", value: 6 },
                  { label: "7", value: 7 },
                  { label: "8", value: 8 },
                ]}
              />
            </FormItem>
            <FormItem
              label="停止位"
              rules={[{ required: false }]}
              name="stopBits"
            >
              <Select
                options={[
                  { label: "1", value: 1 },
                  { label: "1.5", value: 1.5 },
                  { label: "2", value: 2 },
                ]}
              />
            </FormItem>
            <FormItem
              label="校验位"
              rules={[{ required: false }]}
              name="parity"
            >
              <Select
                options={[
                  { label: "None", value: 0 },
                  { label: "Odd", value: 1 },
                  { label: "Even", value: 2 },
                  { label: "Mark", value: 3 },
                  { label: "Space", value: 4 },
                ]}
              />
            </FormItem>
          </>
        ) : (
          <>
            <FormItem
              label="IP 地址"
              rules={[
                { required: true },
                {
                  pattern:
                    /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/,
                  message: "请输入正确的IP地址",
                },
              ]}
              name="ipAddress"
            >
              <Input />
            </FormItem>
            <FormItem
              label="端口"
              rules={[
                { required: true },
                {
                  pattern: /^[0-9]*[1-9][0-9]*$/,
                  message: "请输入正确的端口号",
                },
              ]}
              name="port"
            >
              <Input />
            </FormItem>
          </>
        )}
        <FormItem className="float-right">
          <Button type="submit" theme="primary">
            提交
          </Button>
          <Button type="reset" theme="success" style={{ marginLeft: 12 }}>
            重置
          </Button>
        </FormItem>
      </Form>
    </Drawer>
  );
};
export default GatewayDrawer;
